package com.kll.tv.views

import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.View
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import com.kll.carolinehmibiz.OperationManager
import com.kll.carolinehmibiz.model.AccountModel
import com.kll.carolinehmibiz.model.OperateListener
import com.kll.carolinehmibiz.net.bean.GetDiseaseResponse
import com.kll.carolinehmibiz.net.bean.RefreshTokenResponse
import com.kll.carolinehmibiz.presentation.listener.MainContactServiceProtocol
import com.kll.carolinehmibiz.presentation.listener.SelfHelpConsultationProtocol
import com.kll.carolinehmibiz.presentation.presenter.MainContactServicePresenter
import com.kll.carolinehmibiz.presentation.presenter.SelfHelpConsultationPresenter
import com.kll.tv.R
import com.kll.tv.base.views.BaseActivity
import com.kll.tv.databinding.ActivitySelfHelpConsultationBinding
import com.kll.tv.utils.AppToast
import com.kll.tv.utils.PopWindow
import com.kll.tv.utils.TUICallingService
import com.kll.tv.views.adapter.ConnectServicePopAdapter
import com.kll.tv.views.adapter.DiseasesAdapter
import com.tencent.liteav.trtccalling.model.TUICalling
import com.tencent.liteav.trtccalling.model.impl.TUICallingManager
import com.tencent.liteav.trtccalling.model.util.TUICallingConstants
import com.tencent.qcloud.tuicore.util.ToastUtil

/**
 * 自助问诊页
 */
class SelfHelpConsultationActivity: BaseActivity<SelfHelpConsultationPresenter>(), SelfHelpConsultationProtocol.IView, DiseasesAdapter.OnDiseasesListItemClickListener
, MainContactServiceProtocol.IView {
    private lateinit var binding: ActivitySelfHelpConsultationBinding
    private var adapter: DiseasesAdapter? = null
    private var popConnectServiceWindow: PopWindow? = null
    private var connectServicePopAdapter: ConnectServicePopAdapter? = null
    var mCallName: String? = null
    var mCallType: TUICalling.Type? = null
    private var mainContactServicePresenter: MainContactServicePresenter? = null

    override fun initViewBinding(): View {
        binding = ActivitySelfHelpConsultationBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun createPresenter(): SelfHelpConsultationPresenter {
        return SelfHelpConsultationPresenter(this, this)
    }

    override fun init() {
        // 初始化adapter
        if (adapter == null) {
            val diseasesListManager = GridLayoutManager(this, 4)
            diseasesListManager.orientation = GridLayoutManager.VERTICAL
            binding.rvContent.layoutManager = diseasesListManager
            adapter = DiseasesAdapter(this)
            binding.rvContent.adapter = adapter
            adapter!!.setOnDiseasesListItemClickListener(this)
        }

        mainContactServicePresenter = MainContactServicePresenter(this, this)
        initData()
        initListener()
    }

    private fun initData() {
        mPresenter.getDiseaseList()
        TUICallingService.getInstance(this).login()
    }

    private fun initListener() {
        binding.ivBack.setOnClickListener {
            finish()
        }
        binding.ivBackCircular.setOnClickListener {
            finish()
        }
        // 联系客服
        binding.tvContactService.setOnClickListener {
            // 弹窗
            toShowConnectServicePop()
        }
    }

    // 弹窗
    private var toShowConnectServicePopIsBusying = false
    private fun toShowConnectServicePop() {
        if (toShowConnectServicePopIsBusying) return
        toShowConnectServicePopIsBusying = true
        if (popConnectServiceWindow == null) {
            popConnectServiceWindow = PopWindow(this)
            connectServicePopAdapter = ConnectServicePopAdapter(this, View.OnClickListener { v ->
                when (v.id) {
                    // 语音通话
                    R.id.iv_voice -> {
                        mCallName = TUICallingConstants.TYPE_AUDIO
                        mCallType = TUICalling.Type.AUDIO
                        mainContactServicePresenter!!.getAssignCustomerService()
                    }
                    // 视频通话
                    R.id.iv_video -> {
                        mCallName = TUICallingConstants.TYPE_VIDEO
                        mCallType = TUICalling.Type.VIDEO
                        mainContactServicePresenter!!.getAssignCustomerService()
                    }
                    // 取消
                    R.id.tv_cancel -> {
                        popConnectServiceWindow!!.dismiss()
                    }
                }
            })
            popConnectServiceWindow!!.addView(connectServicePopAdapter)
            popConnectServiceWindow!!.animationStyle = R.style.popwindow_anim_style
        }
        popConnectServiceWindow!!.showAtLocation(binding.root, Gravity.BOTTOM, 0, 0)
        toShowConnectServicePopIsBusying = false
    }

    /**
     * 疾病列表item点击回调
     */
    override fun onDiseasesItemClick(data: GetDiseaseResponse.DiseaseBean) {
        startActivity(Intent(this, DiseaseDetailsActivity::class.java).putExtra("title", data.zh_name).putExtra("url", data.url))
    }

    /**
     * 获取疾病列表成功
     */
    override fun getDiseaseSuccessed(
        isFristPage: Boolean,
        datas: ArrayList<GetDiseaseResponse.DiseaseBean>
    ) {
        if(isFristPage) {
            adapter?.data = datas
        } else {
            adapter?.addData(datas)
        }
    }

    /**
     * 获取疾病列表失败
     */
    override fun getDiseaseFailed(code: Int, message: String) {
        AppToast.show(message, 2000)
        if (code == 102) {
            refreshToken()
        }
        if (code == 101) {
            loginAgain()
        }
    }


    override fun getRoomIdSuccess(tencentUserId: String, roomid: String) {
        if (TUICallingService.getInstance(this).isLogin()) {
            val userIDs = arrayOf(tencentUserId)
            val bundle = Bundle()
            bundle.putString(TUICallingConstants.PARAM_NAME_TYPE, mCallName)
            bundle.putStringArray(TUICallingConstants.PARAM_NAME_USERIDS, userIDs)
            bundle.putString(TUICallingConstants.PARAM_NAME_GROUPID, "")
            TUICallingManager.sharedInstance().call(userIDs, roomid,mCallType)
        } else {
            ToastUtil.toastLongMessage("分配客服失败，请重试！")
        }
    }

    override fun getRoomIdFailed(code: Int, message: String) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show()
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mainContactServicePresenter!!.getAssignCustomerService()
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }
    /**
     * 分配客服成功
     */
    override fun assignCSSuccessed(accountNo: String) {
        mainContactServicePresenter!!.getRoomId(accountNo)
    }

    /**
     * 分配客服加载中
     */
    override fun showAssignCSLoading() {
        Toast.makeText(this, "获取中...", Toast.LENGTH_SHORT).show()
    }

    /**
     * 分配客服失败
     */
    override fun assignCSFailed(code: Int, message: String) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show()
        if (code == 102) {
            // token过期 刷新token
            OperationManager.getInstancce().refreshToken(object : OperateListener {
                override fun onSuccess(state: Int, obj: Any?) {
                    var data = obj as RefreshTokenResponse
                    AccountModel.getInstance(baseContext).updateUserToken(data.token)
                    mainContactServicePresenter!!.getAssignCustomerService()
                }

                override fun onFail(code: Int, message: String) {
                    AppToast.show(message, 2000)
                    if (code == 101) {
                        loginAgain()
                    }
                }

            })
        }
        if (code == 101) {
            loginAgain()
        }
    }

}